/**
 * 询价.COM v1.0.0
 * http://xun-jia.com/
 *
 * Copyright (c) 2009 
 * 四川漾天空网络科技有限公司
 * 成都市天府软件园A2栋3楼
 *
 */
package com.wiretap.util;

import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @author michael
 * 
 * @Email michael_zhao@xun-jia.com
 * 
 * @Date 2009-4-24 上午11:08:27
 * 
 */
public class EncoderUtil implements Serializable {

	private static final long serialVersionUID = 5226904306850666958L;

	/**
	 * 按照指定加密算法加密字符串
	 * 
	 * @param type
	 *            加密算法類型
	 * @param str
	 *            需要加密的字符串
	 * @return
	 */
	public static String encode(String str, String type) {
		try {
			if (null == type || "".equals(type.trim()) || null == str || "".equals(str.trim()))
				return null;
			MessageDigest encoder = MessageDigest.getInstance(type);
			encoder.update(str.getBytes());
			return byte2hex(encoder.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 將此字節數組轉換成16進制字符串
	 * 
	 * @param b
	 * @return
	 */
	private static String byte2hex(byte[] b) {
		String hs = "";
		for (int n = 0; n < b.length; n++) {
			hs += Integer.toHexString(b[n] >>> 4 & 0xF);
			hs += Integer.toHexString(b[n] & 0xF);
		}
		return hs;
	}

	/**
	 * 返回加密后的字符串 key是用于生成密钥的字符串，input是要加密的字符串
	 * 
	 * @param key
	 * @param input
	 * @return
	 */
	public static String getEncryptedString(String key, String input) {
		String base64 = "";
		try {
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, getKey(key));
			byte[] inputBytes = input.getBytes("UTF8");
			byte[] outputBytes = cipher.doFinal(inputBytes);
			BASE64Encoder encoder = new BASE64Encoder();
			base64 = encoder.encode(outputBytes);
		} catch (Exception e) {
			base64 = e.getMessage();
		}
		return base64;
	}

	/**
	 * 返回解密后的字符串 key是用于生成密钥的字符串，input是要解密的字符串
	 * 
	 * @param key
	 * @param input
	 * @return
	 */
	public static String getDecryptedString(String key, String input) {
		String result = null;
		try {
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, getKey(key));
			BASE64Decoder decoder = new BASE64Decoder();
			byte[] raw = decoder.decodeBuffer(input);
			byte[] stringBytes = cipher.doFinal(raw);
			result = new String(stringBytes, "UTF-8");
		} catch (Exception e) {
			result = e.getMessage();
		}
		return result;
	}

	/**
	 * 加密
	 */
	public static String passportEncrypt(String src, String key) {
		Random random = new Random();
		random.setSeed(System.currentTimeMillis());
		String rand = "" + random.nextInt() % 32000;
		String encryptKey = encode(rand, "MD5");
		int ctr = 0;
		String tmp = "";
		for (int i = 0; i < src.length(); ++i) {
			ctr = (ctr == encryptKey.length() ? 0 : ctr);
			tmp += encryptKey.charAt(ctr);
			char c = (char) (src.charAt(i) ^ encryptKey.charAt(ctr));
			tmp += c;
			ctr++;
		}
		String passportKey = passportKey(tmp, key);
		return new sun.misc.BASE64Encoder().encode(passportKey.getBytes());
	}

	/**
	 * 解密
	 */
	public static String passortDecrypt(String src, String key) {
		byte[] bytes = null;
		try {
			bytes = new BASE64Decoder().decodeBuffer(src);
			src = new String(bytes);
		} catch (Exception e) {
			return null;
		}
		src = passportKey(src, key);
		String tmp = "";
		for (int i = 0; i < src.length(); ++i) {
			char c = (char) (src.charAt(i) ^ src.charAt(++i));
			tmp += c;
		}
		return tmp;
	}

	/**
	 * 處理密匙
	 */
	public static String passportKey(String src, String key) {
		String encryptKey = encode(key, "MD5");
		int ctr = 0;
		String tmp = "";
		for (int i = 0; i < src.length(); ++i) {
			ctr = (ctr == encryptKey.length() ? 0 : ctr);
			char c = (char) (src.charAt(i) ^ encryptKey.charAt(ctr));
			tmp += c;
			ctr++;
		}
		return tmp;
	}

	public static String passportEncode(Map<String, String> data) {
		Set<String> keys = data.keySet();
		String ret = "";
		for (String key : keys) {
			ret += key + "=" + data.get(key) + "&";
		}
		if (ret.length() > 0)
			return ret.substring(0, ret.length() - 1);
		return "";
	}

	// 生成key
	public static SecretKey getKey(String s) throws Exception {

		char[] ss = s.toCharArray();
		String sss = "";
		for (int i = 0; i < ss.length; i = i + 2) {
			sss = sss + ss[i];
		}
		SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
		DESKeySpec ks = new DESKeySpec(sss.substring(0, 8).getBytes());
		SecretKey kd = kf.generateSecret(ks);
		return kd;
	}
}
